import { defineStore } from 'pinia'
import { formatTime } from '@/utils'

export const ChatMessage = defineStore('defineStore', {
    state() {
        return {
            isLogin: false,
            showChatBtn: false,
            group: [], // 我的群聊
            contacts: [], //联系人
            newRequestList: [], // 新朋友请求加好友
            chatList: [], // 聊天列表左侧
            chatMessageList: [], // 当前聊天会话记录 --- 对话框
            tagStatus: 'chat', // chat 聊天状态， contacts 联系人状态
            currentChatTargetId: 0, // 当前聊天对象的id
            currentChatName: '', //当前聊天目标名称,
            currentMessageList: [],// 当前过滤完聊天对话
            notReadyMessageCount: 0, // 当前未读消息总数
            chatType: 1, // 当前聊天类型 1对一 2 群聊
        }
    },
    actions: {
        initStoreData() {
            this.showChatBtn = false
            this.contacts = []
            this.newRequestList = []
            this.chatList = []
            this.chatMessageList = []
            this.currentMessageList = []
            this.tagStatus = 'chat'
            this.currentChatName = ''
            this.currentChatTargetId = 0
            this.chatType = 1
            this.notReadyMessageCount = 0
        },
        setStatus(bool) {
            this.isLogin = bool
        },
        addChat(obj) {
            this.groupList[0].messageContent.push(obj)
        },
        setChatBtnStatus(bool) {
            this.showChatBtn = bool
        },
        async getFriendsList() {
            const { results = [] } = await useHttpGet("/api/chat-friends/list")
            this.contacts = (results || []).map(item => ({ ...item, friendsType: 'user' })) || []
        },
        async getFriendsHistoryMessageList(friendId = null) {
            const { results = [] } = await useHttpGet("/api/chat-friends/record/last", {
                params: { friendId }
            })

            if (results?.length) {
                let arr = results.map(item => ({
                    friendId: item.receiverUserId,
                    messageType: 1,
                    messageData: {
                        senderId: item.senderUserId,
                        senderNickname: item.senderUserNickname,
                        senderAvatar: item.senderUserAvatar,
                        sendTime: item.createdAt,
                        receiverId: item.receiverUserId,
                        contentType: item.types,
                        content: item.types == 1 ? item.content : item.imageUrl
                    },
                })).reverse()

                this.chatMessageList = [...this.chatMessageList, ...arr]
                this.updateCurrentMessageList()
                this.updateChatListLastMessage(friendId, results.at(0).content || '')
            }

        },
        updateChatListLastMessage(id = 0, message = '') { // 更新最后一条消息
            let isChat = this.chatList.filter(item => item.friendId === id)
            if (isChat.length) {
                isChat[0].lastMessage = message
            }
        },
        async getGroupHistoryMessageList(groupId = null) {
            const { results = [] } = await useHttpGet("/api/chat-groups/record/last", {
                params: { groupId }
            })

            if (results?.length) {
                let arr = results.map(item => ({
                    friendId: item.groupId,
                    messageType: 2,
                    messageData: {
                        senderId: item.senderUserId,
                        senderNickname: item.senderUserNickname,
                        senderAvatar: item.senderUserAvatar,
                        sendTime: item.createdAt,
                        groupId: item.groupId,
                        contentType: item.types,
                        content: item.content
                    },
                })).reverse()

                this.chatMessageList = [...this.chatMessageList, ...arr]
                this.updateCurrentMessageList()
                this.updateChatListLastMessage(groupId, results.at(0).content || '')
            }

            // console.log(results, '----------results----------');

        },
        async getNewRequestFriends() {
            let { results = [] } = await useHttpGet('/api/chat-friends/request/list')
            this.newRequestList = results || []
        },
        async getGroupList() {
            let data = await useHttpGet('/api/chat-groups/list')
            this.group = (data || []).map(item => ({ ...item, friendsType: 'groupChat' })) || []

        },
        readyAllMessage(friendId) {
            this.chatList.forEach(item => {
                if (item.friendId === friendId) {
                    item.value = 0
                }
            })
        },
        updateNotReadyMessageCount() { // 更新未读消息总数
            let count = 0
            this.chatList.forEach(item => {
                if (item.friendId !== this.getUserInfo().id) {
                    count += item.value
                }

            })
            this.notReadyMessageCount = count
        },
        async addChatList(chat) { // 新增聊天列表
            if (!chat.pushMessage) {
                this.currentChatTargetId = chat.friendId
            }

            let isChat = this.chatList.filter(item => item.friendId === chat.friendId)
            if (!isChat.length) {
                this.chatList.push({ ...chat, loading: false })
                if (chat.chatType === 1) {
                    this.getFriendsHistoryMessageList(chat.friendId)
                } else if (chat.chatType === 2) {
                    this.getGroupHistoryMessageList(chat.friendId)
                }

            } else {
                if (chat.friendId !== this.currentChatTargetId) {
                    isChat[0].value = isChat[0].value + 1

                }
                isChat[0].time = formatTime(new Date(), 'HH:mm')
                if (chat.contentType === 2) {
                    isChat[0].lastMessage = '图片'
                } else {
                    isChat[0].lastMessage = chat.lastMessage ? chat.lastMessage : chat?.messageData?.lastMessage
                }

            }

            if (chat.senderId !== this.getUserInfo()?.id) {
                let isChat = this.chatList.filter(item => item.friendId === chat.senderId)
                if (isChat.length) {
                    if (chat.contentType === 2) {
                        isChat[0].lastMessage = '图片'
                    } else {
                        isChat[0].lastMessage = chat.lastMessage
                    }
                    isChat[0].time = formatTime(new Date(), 'HH:mm')
                }
            }
            // console.log(this.chatList, chat, 'left-slider', isChat);

            this.updateNotReadyMessageCount()
        },
        addChatMessage(chat) { // 添加当前聊天对象记录  —— 右侧消息内容
            // let isChat = this.chatMessageList.filter(item => item.uuid === chat.uuid)

            if (chat.friendId) {
                let isChat = this.chatList.filter(item => item.friendId === chat.friendId)
                if (isChat.length) {
                    this.chatMessageList.push(chat)
                }

                let base = {
                    friendAvatar: chat.messageData.senderAvatar,
                    ready: true,
                    value: 1,
                    pushMessage: true,
                    contentType: chat.messageData.contentType || 1,
                    time: formatTime(new Date(), 'HH:mm',),
                    lastMessage: chat.messageData.content,
                    chatType: chat.messageType,
                    friendNickname: chat.messageType === 2 ? chat.messageData.groupName : (chat.messageData.friendNickname || chat.messageData.senderNickname),
                    friendId: chat.messageType === 2 ? chat.messageData.groupId : chat.messageData.senderId,
                    senderId: chat.messageData.receiverId
                }
                if (this.chatType === 1) {
                    this.addChatList({
                        ...base
                    })
                } else if (this.chatType === 2) {
                    this.addChatList({
                        ...base
                    })
                }

            }
            // console.log(this.chatMessageList, chat, '推入消息');

            // console.log(this.chatMessageList, chat, '--------------------');
        },

        removeCurrentChat(friendId) { //删除当前好友时同时删除聊天记录
            this.chatList = this.chatList.filter(item => item.friendId !== friendId)
            this.currentChatTargetId = 0
            this.updateCurrentMessageList()
        },

        updateCurrentMessageList() {
            let userId = this.getUserInfo()?.id || null
            if (!userId) {
                this.chatMessageList = []
                return
            }
            this.currentMessageList = []
            let chat = []
            if (this.chatType === 1) {
                chat = this.chatMessageList.filter(item =>
                    ((item.messageData.senderId === userId && item.friendId === this.currentChatTargetId)
                        ||
                        (item.messageData.senderId === this.currentChatTargetId && item.messageData.receiverId === userId))
                    &&
                    item.messageType === 1
                )
            } else if (this.chatType === 2) {
                chat = this.chatMessageList.filter(item =>
                    ((item.messageData.senderId === userId && this.currentChatTargetId == item.friendId) ||
                        this.currentChatTargetId == item.messageData.groupId || this.currentChatTargetId == item.friendId)
                    && item.messageType === 2
                )
            }

            if (chat.length > 50) {
                this.currentMessageList = chat.splice(0, 50)
            } else {
                this.currentMessageList = chat
            }


            // console.log(this.chatMessageList, 'fool', this.currentChatTargetId);
            // console.log(this.currentMessageList, 'filter-----------------------', this.chatType);

        },

        removeCurrentChatMessage(friendId) { // 删除当前联系人时同时删除聊天消息
            let userId = this.getUserInfo()?.id || null
            if (!userId) {
                this.chatMessageList = []
                return
            }
            if (this.chatType === 1) {
                let chat = this.chatMessageList.filter(item =>
                    ((item.messageData.senderId === userId && item.friendId === friendId)
                        ||
                        (item.messageData.senderId === friendId && item.messageData.receiverId === userId))
                    &&
                    item.messageType === 1
                )
                if (chat?.length) {
                    let ids = chat.map(item => item.friendId)
                    this.chatMessageList = this.chatMessageList.filter(item => !ids.includes(item.friendId))
                }

                // console.log(chat, '66666666', this.chatMessageList);

            }
        },

        changeTagStatus(status) { // 切换消息和联系人
            this.tagStatus = status
        },
        setCurrentChatName(name) {
            this.currentChatName = name
        },
        setChatType(type) { // 设置当前聊天类型  1 用户和用户  2 群聊
            this.chatType = type
        },
        setCurrentTargetFriendId(id) { // 设置当前聊天好友 friendId
            this.currentMessageList = []
            this.currentChatTargetId = id
            this.updateNotReadyMessageCount()
            this.updateCurrentMessageList()
        },
        getUserInfo() {
            let user = JSON.parse(localStorage.getItem('user') || "{}")
            return user
        },
        getToken() {
            return localStorage.getItem('token') || ''
        }
    },
    getters: {
        isShowBadge() {
            return this.newRequestList.length > 0 ? true : false
        },
        getCurrentChatMessage() { // 获取当前聊天对象的记录
            // console.log(this.chatMessageList, 333);
            // console.log(`${this.getUserInfo().id},${this.currentChatTargetId}`);

            let chat = this.chatMessageList.filter(item => item.uuid == `${this.getUserInfo().id},${this.currentChatTargetId}`)
            if (chat.length) {
                return chat[0].messageContent
            }
            return []
        },
        currentFriendsId() {
            return this.currentChatTargetId
        }
    }
})